/*
 * Create:      柿子
 * CreateDate:  2022/07/20
 * Describe：   视光管理系统 - 视光单查询/验光单查询
 * */
import React, { Component } from 'react';
import { Card, Row, Col, Select, Input, Button, message, Divider, Tooltip } from 'antd';
import { $http } from 'containers/config/https';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import ViewWrittenMedicalRecords from './component/ViewWrittenMedicalRecords';
import GetPatientInformation from './component/GetPatientInformation';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconInquire from 'assets/images/icon_Inquire.png';
import './style/index.less';

class OptometrySlipQuery extends Component {
  constructor(props) {
    super(props)
    this.state = {
      queryParam: {
        endDate: moment().format('YYYY-MM-DD'), // 开单日期
        startDate: moment().format('YYYY-MM-DD'),
        ordLocID: undefined, // 开单科室
        ordDoctorID: undefined, // 开单医生
        optometryNo: undefined, // 检查单号
        optomeDoctorID: undefined, // 验光师
        optomeTypeID: undefined, // 验光类型
        admType: undefined, // 就诊类型
        prescStatus: '', // 开具处方
      },
      columns: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      totalWidth: 2100,
      loading: false,
      selectData: {},
      cardType: '',
      cardSelectData: [], // 卡类型下拉数据
      exportLoading: false
    };
    this.staticColumns = [{
      key: 1,
      title: '验光单号',
      dataIndex: 'optometryNo',
      align: "center",
      width: 200
    }, {
      key: 2,
      title: '病人ID',
      dataIndex: 'patNo',
      align: "center",
      width: 150
    }, {
      key: 3,
      title: '姓名',
      dataIndex: 'patName',
      align: "center",
      width: 100
    }, {
      key: 4,
      title: '性别',
      dataIndex: 'patSexDesc',
      align: "center",
      width: 100
    }, {
      key: 5,
      title: '年龄',
      dataIndex: 'patAge',
      align: "center",
      width: 100
    }, {
      key: 6,
      title: '门诊诊断',
      dataIndex: 'admDiag',
      align: "center",
      width: 100
    }, {
      key: 7,
      title: '验光日期',
      dataIndex: 'optometryDate',
      align: "center",
      width: 150
    }, {
      key: 8,
      title: '开单科室',
      dataIndex: 'ordLocDesc',
      align: "center",
      width: 100
    }, {
      key: 9,
      title: '开单医生',
      dataIndex: 'ordDoctor',
      align: "center",
      width: 100
    }, {
      key: 10,
      title: '验光类型',
      dataIndex: 'optometryTypeDesc',
      align: "center",
      width: 100
    }, {
      key: 11,
      title: 'OD',
      dataIndex: 'OD',
      align: "center",
      width: 100
    }, {
      key: 12,
      title: 'OS',
      dataIndex: 'OS',
      align: "center",
      width: 100
    }, {
      key: 13,
      title: 'OD小孔',
      dataIndex: 'ODOstiole',
      align: "center",
      width: 100
    }, {
      key: 14,
      title: 'OS小孔',
      dataIndex: 'OSOstiole',
      align: "center",
      width: 100
    }, {
      key: 15,
      title: 'OD戴镜',
      dataIndex: 'ODWearGlasses',
      align: "center",
      width: 100
    }, {
      key: 16,
      title: 'OS戴镜',
      dataIndex: 'OSWearGlasses',
      align: "center",
      width: 100
    }, {
      key: 17,
      title: 'OD眼压',
      dataIndex: 'ODIOP',
      align: "center",
      width: 100
    }, {
      key: 18,
      title: 'OS眼压',
      dataIndex: 'OSIOP',
      align: "center",
      width: 100
    }, {
      key: 19,
      title: '验光室',
      dataIndex: 'inspectRoomDesc',
      align: "center",
      width: 100
    }]
  }

  componentDidMount() {
    this.getDefaultData();
    this.getColumnsData();
  }

  // 获取卡类型下拉框数据
  getDefaultData = () => {
    let { queryParam } = this.state;
    let data = {
      params: [{}]
    }
    $http.post('urlS', this, {
      code: '17050001',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let defaultValue = '';
          let resultDefaultValue = res.result && res.result.defaultValue ? res.result.defaultValue : {}; // 初始化默认值
          let cardSelectData = res.result?.cardType || [];
          for (var i = 0; i < cardSelectData.length; i++) {
            if (cardSelectData[i].defaultFlag === 'Y') {
              defaultValue = cardSelectData[i].id;
            }
          }
          queryParam.startDate = resultDefaultValue?.defaultStartDate || queryParam.startDate;
          queryParam.endDate = resultDefaultValue?.defaultEndDate || queryParam.endDate;
          this.setState({
            queryParam,
            cardSelectData,
            cardType: defaultValue,
            selectData: res.result,
          }, () => {
            // this.getTableData('N'); // 不默认查询
          })
        } else {
          // this.getTableData('N'); // 不默认查询
        }
      }
    })
  }

  // 获取表头数据
  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OptometrySlipQuery',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              return (
                <Tooltip title={text}>
                  <span
                    className={(record.sendStatus === '发送失败' ? 'common-record-delete-span' : (record.sendStatus === '未发送' ? 'osq-not-sent' : '')) + ' ellipsis'}
                    style={{ width: '100%', display: 'block' }}
                  >
                    {text}
                  </span>
                </Tooltip>
              );
            },
          }
        })
        this.setState({ columns, totalWidth: res?.totalWidth });
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 查询
  handleQuery = (isTips) => {
    this.setState({ page: 1 }, () => {
      this.getTableData(isTips);
    })
  }

  // 修改查询接口入参
  handleInputChange = (e, dataIndex, isQuery) => {
    let { queryParam } = this.state;
    queryParam[dataIndex] = e;
    this.setState({ queryParam }, () => {
      isQuery === 'N' ? '' : this.handleQuery();
    })
  }

  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = (isTips) => {
    if (isTips !== 'export') {
      this.setState({ loading: true });
    } else {
      this.setState({ exportLoading: true });
    }
    let { page, pageSize, queryParam, columns } = this.state;
    let patID = this.patientRef && this.patientRef.getPatientID();
    let data = {
      params: [{
        ...queryParam,
        // patID,
        patInfo: patID,
      }],
      pagination: [{
        pageSize: isTips === 'export' ? 10000 : pageSize,
        currentPage: isTips === 'export' ? 1 : page
      }]
    }
    $http.post('urlS', this, {
      code: '17050002',
      data,
      success: function (res) {
        if (res.errorCode === '0') {
          let nTableData = res.result?.rows || [];
          if (isTips === 'export') {
            this.setState({ exportLoading: false });
            handleExcel.exportExcel(columns && columns.length > 0 ? columns : this.staticColumns, nTableData, '验光单列表')
          } else {
            this.setState({ tableData: nTableData, total: res.result?.total || 0, loading: false });
            if (!(nTableData && nTableData.length > 0)) {
              isTips === 'N' ? '' : message.error('未查询到数据');
            }
          }
        } else {
          if (isTips !== 'export') {
            this.setState({ tableData: [], total: 0, loading: false, exportLoading: false });
          }
        }
      },
      error: function () {
        if (isTips !== 'export') {
          this.setState({ tableData: [], total: 0, loading: false, exportLoading: false });
        }
      }
    })
  }

  // 导出
  handleExport = () => {
    this.getTableData('export');
  }

  // 发送
  handleSend = async (record) => {
    try {
      let data = {
        params: [{
          optometryRecordID: record?.optometryRecordID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17020011', data);
      message.success(res?.errorMessage || '发送成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 查看验光单
  handleLook = (record) => {
    this.viewWrittenRecordsRef && this.viewWrittenRecordsRef.modifyVisible(true, record);
  }

  render() {
    let { queryParam, page, total, loading, totalWidth, tableData, columns, cardType, cardSelectData, selectData, exportLoading } = this.state;

    // 列表操作
    const operationObj = {
      width: 180,
      title: '操作',
      align: 'left',
      key: 'operation',
      fixed: 'right',
      render: (text, record) => (
        <span style={{ paddingLeft: 10 }}>
          {/* {record?.sendFlag !== 'Y' ? ( // Y是发送成功，N是发送失败，''是没发送
            <> */}
          <span className="span" style={{ color: record?.sendFlag === 'Y' ? '#fa8c17' : '' }} onClick={(e) => this.handleSend(record, e)}>
            {record?.sendFlag === 'Y' ? '重新发送' : '发送验光单'}
          </span>
          <Divider type="vertical" />
          {/* </>
          ) : ''} */}
          <span className="span" onClick={(e) => this.handleLook(record, e)}>
            查看单据
          </span>
        </span>
      ),
    };
    return (
      <div className="optometry-slip-query">
        <Row>
          <Col span={5}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconInquire} alt="" />
                    搜索条件
                  </div>
                )}
              >
                <div style={{ height: store.getState().tableHeight.y + 182 + 'px' }}>
                  <GetPatientInformation
                    isEnter="Y"
                    patWidth="75%"
                    parLabelClass="osq--input-label"
                    queryType="fuzzySearch"
                    cardType={cardType}
                    cardSelectData={cardSelectData}
                    onRef={ref => this.patientRef = ref}
                    handleQuery={this.handleQuery}
                  />
                  <div className="osq-input-item">
                    <span>开单科室：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      value={queryParam?.ordLocID}
                      onChange={(e) => this.handleInputChange(e, 'ordLocID')}
                    >
                      {React.$SelectOptions(selectData?.ordLoc || [])}
                    </Select>
                  </div>
                  <div className="osq-input-item">
                    <span>开单医生：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      value={queryParam?.ordDoctorID}
                      onChange={(e) => this.handleInputChange(e, 'ordDoctorID')}
                    >
                      {React.$SelectOptions(selectData?.ordDoctor || [])}
                    </Select>
                  </div>
                  <div className="osq-input-item flex-align-items">
                    <span>验光日期：</span>
                    <RangeDatePicker
                      label=""
                      width="100%"
                      totalwidth="75%"
                      format="YYYY-MM-DD"
                      endDate={queryParam?.endDate}
                      startDate={queryParam?.startDate}
                      endChange={(e) => this.handleInputChange(e, 'endDate')}
                      startChange={(e) => this.handleInputChange(e, 'startDate')}
                    />
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className='osq--input-label'>验光单号：</span>
                    <Input
                      allowClear
                      value={queryParam?.optometryNo}
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      onChange={(e) => this.handleInputChange(e.target.value, 'optometryNo', 'N')}
                      onPressEnter={this.handleQuery}
                    />
                  </div>

                  <div className="osq-input-item">
                    <span>验光医生：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      value={queryParam?.optomeDoctorID}
                      onChange={(e) => this.handleInputChange(e, 'optomeDoctorID')}
                    >
                      {React.$SelectOptions(selectData?.optomeDoctor || [])}
                    </Select>
                  </div>
                  <div className="osq-input-item">
                    <span>验光类型：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      value={queryParam?.optomeTypeID}
                      onChange={(e) => this.handleInputChange(e, 'optomeTypeID')}
                    >
                      {React.$SelectOptions(selectData?.optomeType || [])}
                    </Select>
                  </div>
                  <div className="osq-input-item">
                    <span>就诊类型：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      value={queryParam?.admType}
                      onChange={(e) => this.handleInputChange(e, 'admType')}
                    >
                      {React.$SelectOptions(selectData?.admType || [])}
                    </Select>
                  </div>
                  <div className="osq-input-item">
                    <span>开具处方：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      value={queryParam?.prescStatus}
                      onChange={(e) => this.handleInputChange(e, 'prescStatus')}
                    >
                      {React.$SelectOptions(selectData?.prescStatus || [])}
                    </Select>
                  </div>
                  <div className="flex-center">
                    <Button ghost type="primary" style={{ marginRight: 15 }} loading={exportLoading} onClick={this.handleExport}>导出</Button>
                    <Button type="primary" onClick={this.handleQuery}>查询</Button>
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={19}>
            <Card
              size="small"
              bordered={false}
              title={(
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt="" />
                  验光单列表
                </div>
              )}
              className="table-body-height"
            >
              <PublicTablePagination
                param={{
                  page,
                  total,
                  loading,
                  x: totalWidth,
                  data: tableData,
                  pageSize: '20',
                  rowKey: 'optometryRecordID',
                  componentName: 'OptometrySlipQuery',
                  y: store.getState().tableHeight.y + 91,
                  height: store.getState().tableHeight.y + 141 + 'px',
                  columns: columns && columns.length > 0 ? [...columns, operationObj] : [...this.staticColumns, operationObj],
                }}
                compilePage={this.compilePage}
                getColumns={this.getColumnsData}
              />
            </Card>
          </Col>
        </Row>

        <ViewWrittenMedicalRecords
          title="查看验光单"
          onRef={ref => this.viewWrittenRecordsRef = ref}
        />
      </div>
    );
  }
};

export default OptometrySlipQuery;